import telnetlib
import time
import re


def Jiaohuanji():
    username = 'xcchen'
    password = '!z5521159'
    tip = '192.168.110.251'
    cmd = 'display arp'
    confComplete = ""
    moreReg = '  ---- More ----'
    try:
        tn = telnetlib.Telnet(tip,port=23,timeout=50)
        tn.read_until(b"Username:")
        tn.write(username.encode('ascii') + b'\n')
        time.sleep(0.5)
        tn.read_until(b"Password:")
        tn.write(password.encode('ascii') + b'\n')
        time.sleep(0.5)
    except Exception as e:
        print(e)
        tn.close()


    tn.write(cmd.encode('ascii') + b'\n')
    time.sleep(0.5)
    msg = tn.read_very_eager().decode('utf-8')
    moerFlag = re.search(moreReg, msg)
    confComplete = re.sub(moreReg, ' ', confComplete)
    confComplete = confComplete + msg

    while (moerFlag):
        tn.write(' '.encode('ascii'))
        time.sleep(0.2)
        msg = tn.read_very_eager().decode('utf-8')
        moerFlag = re.search(moreReg, msg)
        confComplete = re.sub(moreReg, ' ', confComplete)
        confComplete += msg
    # tn.write('exit'.encode('ascii'))
    tn.close()
    # print(confComplete)
    tn.close()
    left = confComplete.find('192')
    confComplete = confComplete[left:]
    right = confComplete.find("------------------------------------------------------------------------------")
    confComplete = confComplete[:right]
    print(confComplete)



    ccd = str(confComplete).split()
    try:
        while ccd.index("\x1b[42D"):

            ccd.remove(ccd[ccd.index("\x1b[42D")])
    except Exception as e:
        pass
    print(ccd)
    list1 = []
    list2 = []
    for ccd_number in range(len(ccd)):

        if re.match('((.*)\.){3}(.*)', ccd[ccd_number]):
            if "\x1b[42D" in ccd[ccd_number]:
                ccd[ccd_number] = ccd[ccd_number].replace("\x1b[42D","")
            list1.append(ccd[ccd_number])
            list1.append(ccd[ccd_number + 1])

            if ccd[ccd_number + 2] == 'I':
                list1.append('0')
                list1.append('-')
                list1.append(ccd[ccd_number + 4])
                list1.append('-')

            else:
                list1.append(ccd[ccd_number + 2])
                list1.append(ccd[ccd_number + 3])
                list1.append(ccd[ccd_number + 4])
                list1.append(ccd[ccd_number + 5])

            list2.append(list1)
            list1 = []

    print(list2)

if __name__ == '__main__':
    Jiaohuanji()